﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Als.Utils.Extensions
{
    public static class PageExtensions
    {
        #region 分页扩展

        /// <summary>
        /// 分页扩展
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="allItems"></param>
        /// <param name="pageIndex">索引</param>
        /// <param name="pageSize">条数</param>
        /// <param name="isAlwaysReturnLastPageData">是否始终返回最后一页数据(当pageindex大于总页数时候)</param>
        /// <returns></returns>
        public static PagedList<T> GetPagedList<T>(this IEnumerable<T> allItems, int pageIndex, int pageSize, bool isAlwaysReturnLastPageData = false)
        {
            if (pageIndex < 1)
                pageIndex = 1;
            var itemIndex = (pageIndex - 1) * pageSize;
            var enumerable = allItems as T[] ?? allItems.ToArray();
            var totalItemCount = enumerable.Count();
            if (isAlwaysReturnLastPageData)
            {
                while (totalItemCount <= itemIndex && pageIndex > 1)
                {
                    itemIndex = (--pageIndex - 1) * pageSize;
                }
            }
            var pageOfItems = enumerable.Skip(itemIndex).Take(pageSize);
            return new PagedList<T>(pageOfItems, pageIndex, pageSize, totalItemCount);
        }

        #endregion
    }

    #region 分页类

    public class PagedList<T> : List<T>
    {
        public PagedList(IEnumerable<T> currentPageItems, int pageIndex, int pageSize, int totalItemCount)
        {
            AddRange(currentPageItems);
            TotalItemCount = totalItemCount;
            CurrentPageIndex = pageIndex;
            PageSize = pageSize;
        }
        public int CurrentPageIndex { get; set; }

        public int PageSize { get; set; }

        public int TotalItemCount { get; set; }

        public int TotalPageCount => (int)Math.Ceiling(TotalItemCount / (double)PageSize);

        public int StartItemIndex => (CurrentPageIndex - 1) * PageSize + 1;

        public int EndItemIndex => TotalItemCount > CurrentPageIndex * PageSize ? CurrentPageIndex * PageSize : TotalItemCount;
    }

    #endregion

}
